import 'package:fluent_ui/fluent_ui.dart';

import '../../api/test_batch_api.dart';
import '../../components/data_table.dart';
import '../../global_setting.dart';
import '../../model/test_batch_model.dart';
import '../../utils/loading_utils.dart';
import '../app/app_dict_data.dart';

abstract class TestBatchField {}

/// 考试批次:查询字段
enum TestBatchQueryField implements TestBatchField {
  semester('学年学期'),
  grade('年级'),
  level('层次'),
  name('名称'),
  status('状态');

  final String label;

  const TestBatchQueryField(this.label);
}

/// 考试批次:输入字段
enum TestBatchInputField implements TestBatchField {
  name('名称', checked: true),
  semester('学年学期', checked: true),
  grade('年级', checked: true),
  level('层次', checked: true),
  schools('学校集合'),
  remark('备注'),
  status('状态', isAdd: false);

  final String label;
  final bool checked, isAdd;

  const TestBatchInputField(
    this.label, {
    this.checked = false,
    this.isAdd = true,
  });

  String? validHandler<T>(final T? val) {
    if (checked) {
      if (val == null) {
        return '$label不能为空';
      }
      if (val is String) {
        return val.isEmpty ? '$label不能为空' : null;
      }
      if (val is List) {
        return val.isEmpty ? '$label不能为空' : null;
      }
    }
    return null;
  }
}

///考试批次:视图模型
class TestBatchViewModel extends ChangeNotifier {
  //查询字段
  final _queryFields = <TestBatchQueryField, TextEditingController>{
    for (var field in TestBatchQueryField.values)
      field: TextEditingController(),
  };

  //输入字段
  final _inputFields = <TestBatchInputField, TextEditingController>{
    for (var field in TestBatchInputField.values)
      field: TextEditingController(),
  };

  //获取控制器
  TextEditingController? getController<T extends TestBatchField>(
      final T field) {
    //查询字段
    if (field is TestBatchQueryField) {
      return _queryFields[field];
    }
    //输入字段
    if (field is TestBatchInputField) {
      return _inputFields[field];
    }
    return null;
  }

  ///获取字段值
  String? getFieldValue<T extends TestBatchField>(final T field) {
    final ctr = getController(field);
    if (ctr != null) {
      return ctr.text;
    }
    return null;
  }

  ///设置字段值
  void setFieldValue<T extends TestBatchField>(T field, String? val) {
    final controller = getController(field);
    if (controller != null) {
      controller.text = val ?? '';
    }
  }

  final _statusOpts = <ComboBoxItem<String>>[];

  ///获取状态选项集合
  List<ComboBoxItem<String>> get statusOpts => _statusOpts;

  ///加载字典
  void _loadDict(final List<Future<dynamic>> futures) {
    //状态
    if (_statusOpts.isEmpty) {
      final future = appDictData.buildOpts('status').then((opts) {
        if (opts.isNotEmpty) {
          _statusOpts.addAll(opts);
        }
      });
      futures.add(future);
    }
  }

  void loadInit({final VoidCallback? afterHandler}) async {
    final futures = <Future<dynamic>>[];
    //加载字典
    _loadDict(futures);
    //请求同步
    if (futures.isNotEmpty) {
      await Future.wait(futures);
      //触发通知
      notifyListeners();
    }
    //回调处理
    if (afterHandler != null) {
      afterHandler.call();
    }
  }

  ///清空查询字段
  void cleanQueryFields() {
    for (var ctl in _queryFields.values) {
      ctl.clear();
    }
  }

  ///清空输入字端
  void cleanInputFields() {
    for (var ctl in _inputFields.values) {
      ctl.clear();
    }
  }

  ///分页查询模型
  final queryModel = PageModel<TestBatchItemRes>();

  ///分页查询
  void query() async {
    try {
      loading.showLoading();
      //查询处理
      final grade = getFieldValue(TestBatchQueryField.grade);
      final status = getFieldValue(TestBatchQueryField.status);
      final req = TestBatchQueryReq(
        tenantId: globalSetting.tenant,
        semesterId: getFieldValue(TestBatchQueryField.semester) ?? '',
        gradeVal: int.tryParse(grade ?? '') ?? -1,
        levelId: getFieldValue(TestBatchQueryField.level) ?? '',
        name: getFieldValue(TestBatchQueryField.name) ?? '',
        status: int.tryParse(status ?? '') ?? -1,
      );
      final res = await testBatchApi.query(req);
      if (res.isSuccessed) {
        queryModel.buildResData(res);
      }
      debugPrint('testBatchApi.query(req:${req.toMap()})=>$res');
    } finally {
      loading.dismiss();
    }
  }

  ///加载数据
  void getInfoById(final String id) async {
    try {
      loading.showLoading();
      //加载数据
      final res = await testBatchApi.info(id);
      if (res.isSuccessed) {
        setFieldValue(TestBatchInputField.name, res.name);
        setFieldValue(TestBatchInputField.remark, res.remark);
        setFieldValue(TestBatchInputField.semester, res.semesterId);
        setFieldValue(TestBatchInputField.grade, '${res.gradeVal}');
        setFieldValue(TestBatchInputField.level, res.levelId);
        setFieldValue(TestBatchInputField.status, '${res.status}');
        //触发通知
        notifyListeners();
        return;
      }
      final String err;
      if ((err = res.retMessage).isNotEmpty) {
        loading.showToast(err);
      }
    } finally {
      loading.dismiss();
    }
  }

  ///新增处理
  void onAddHandler(final VoidCallback handler) async {
    try {
      loading.showLoading();
      //新增处理
      final gradeVal = getFieldValue(TestBatchInputField.grade);
      final schools = getFieldValue(TestBatchInputField.schools);
      final req = TestBatchAddReq(
        tenantId: globalSetting.tenant,
        name: getFieldValue(TestBatchInputField.name) ?? '',
        remark: getFieldValue(TestBatchInputField.remark) ?? '',
        semesterId: getFieldValue(TestBatchInputField.semester) ?? '',
        gradeVal: int.tryParse(gradeVal ?? '') ?? 0,
        levelId: getFieldValue(TestBatchInputField.level) ?? '',
        schools: (schools as List<int>),
      );
      final res = await testBatchApi.add(req);
      if (res.isSuccessed) {
        cleanInputFields();
        handler.call();
        return;
      }
      final String err;
      if ((err = res.retMessage).isNotEmpty) {
        loading.showToast(err);
      }
    } finally {
      loading.dismiss();
    }
  }

  ///修改处理
  void onModifyHandler(final String id, final VoidCallback handler) async {
    try {
      loading.showLoading();
      //修改处理
      final gradeVal = getFieldValue(TestBatchInputField.grade);
      final schools = getFieldValue(TestBatchInputField.schools);
      final status = getFieldValue(TestBatchInputField.status);
      final req = TestBatchModifyReq(
        id: id,
        name: getFieldValue(TestBatchInputField.name) ?? '',
        remark: getFieldValue(TestBatchInputField.remark) ?? '',
        semesterId: getFieldValue(TestBatchInputField.semester) ?? '',
        gradeVal: int.tryParse(gradeVal ?? '') ?? 0,
        levelId: getFieldValue(TestBatchInputField.level) ?? '',
        schools: (schools as List<int>),
        status: int.tryParse(status ?? '') ?? 1,
      );
      final res = await testBatchApi.modify(req);
      if (res.isSuccessed) {
        cleanInputFields();
        handler.call();
        return;
      }
      final String err;
      if ((err = res.retMessage).isNotEmpty) {
        loading.showToast(err);
      }
    } finally {
      loading.dismiss();
    }
  }

  ///删除处理
  void onDeleteHandler(final String id) async {
    try {
      loading.showLoading();
      //删除
      final res = await testBatchApi.delete(id);
      if (res.isSuccessed) {
        query();
        return;
      }
      final String err;
      if ((err = res.retMessage).isNotEmpty) {
        loading.showToast(err);
      }
    } finally {
      loading.dismiss();
    }
  }
}
